#include "appointmentwidget.h"
#include "ui_appointmentwidget.h"
#include "../../network/networkclient.h"
#include <QMessageBox>
#include <QJsonArray>
#include <QPushButton>
#include <QHBoxLayout>
#include <QLabel>
#include <QMovie>
#include <QTimer>

AppointmentWidget::AppointmentWidget(const Doctor& doctor, QWidget *parent) :
    QWidget(parent),
    ui(new Ui::AppointmentWidget),
    m_doctor(doctor),
    m_loadingLabel(nullptr),
    m_isLoading(false) {
    ui->setupUi(this);
    
    // 设置表格
    ui->appointmentTable->setColumnCount(7);
    ui->appointmentTable->setHorizontalHeaderLabels(
        {"预约ID", "患者姓名", "预约时间", "状态", "症状描述", "操作", "患者ID"});
    ui->appointmentTable->setEditTriggers(QAbstractItemView::NoEditTriggers);
    ui->appointmentTable->setSelectionBehavior(QAbstractItemView::SelectRows);
    
    // 设置列宽模式
    ui->appointmentTable->horizontalHeader()->setSectionResizeMode(QHeaderView::Interactive);
    ui->appointmentTable->setColumnWidth(0, 80);
    ui->appointmentTable->verticalHeader()->setDefaultSectionSize(40);
    ui->appointmentTable->setColumnWidth(1, 120);
    ui->appointmentTable->setColumnWidth(2, 150);
    ui->appointmentTable->setColumnWidth(3, 100);
    ui->appointmentTable->horizontalHeader()->setSectionResizeMode(4, QHeaderView::Stretch); // 症状描述自动拉伸
    ui->appointmentTable->setColumnWidth(5, 280);  // 操作列（两个按钮需要更宽）
    ui->appointmentTable->setColumnWidth(6, 0);    // 隐藏患者ID列
    ui->appointmentTable->setColumnHidden(6, true);
    
    // 隐藏行号列避免乱码
    ui->appointmentTable->verticalHeader()->setVisible(false);
    
    // 创建加载提示标签
    m_loadingLabel = new QLabel(this);
    m_loadingLabel->setText("🔄 正在加载数据...");
    m_loadingLabel->setAlignment(Qt::AlignCenter);
    m_loadingLabel->setStyleSheet(
        "QLabel { "
        "  background-color: rgba(255, 255, 255, 220); "
        "  border: 2px solid #4CAF50; "
        "  border-radius: 8px; "
        "  padding: 20px; "
        "  font-size: 16px; "
        "  color: #4CAF50; "
        "  font-weight: bold; "
        "}"
    );
    m_loadingLabel->hide();
    
    // 设置默认日期为今天
    ui->dateEdit->setDate(QDate::currentDate());
    
    // 连接信号
    connect(&NetworkClient::instance(), &NetworkClient::messageReceived,
            this, &AppointmentWidget::onMessageReceived);
    
    // 加载今天的预约
    loadAppointments();
}

AppointmentWidget::~AppointmentWidget() {
    delete ui;
}

void AppointmentWidget::on_dateEdit_dateChanged(const QDate& date) {
    Q_UNUSED(date);
    loadAppointments();
}

void AppointmentWidget::on_refreshButton_clicked() {
    // 强制刷新时清除缓存
    m_cache.clear();
    qDebug() << "手动刷新 - 已清除缓存";
    loadAppointments();
}

bool AppointmentWidget::getCachedData(const QDate& date, QJsonArray& data) {
    QString cacheKey = date.toString("yyyy-MM-dd");
    
    if (!m_cache.contains(cacheKey)) {
        return false;
    }
    
    const CacheEntry& entry = m_cache[cacheKey];
    
    // 检查缓存是否过期
    QDateTime now = QDateTime::currentDateTime();
    qint64 age = entry.timestamp.secsTo(now);
    
    if (age > CACHE_DURATION_SECONDS) {
        qDebug() << "缓存已过期 - 年龄:" << age << "秒";
        m_cache.remove(cacheKey);
        return false;
    }
    
    data = entry.data;
    return true;
}

void AppointmentWidget::cacheData(const QDate& date, const QJsonArray& data) {
    QString cacheKey = date.toString("yyyy-MM-dd");
    
    CacheEntry entry;
    entry.data = data;
    entry.timestamp = QDateTime::currentDateTime();
    
    m_cache[cacheKey] = entry;
    qDebug() << "已缓存数据 - 日期:" << cacheKey << "记录数:" << data.size();
}

void AppointmentWidget::loadAppointments() {
    QDate selectedDate = ui->dateEdit->date();
    
    // 尝试从缓存获取数据
    QJsonArray cachedData;
    if (getCachedData(selectedDate, cachedData)) {
        qDebug() << "使用缓存数据 - 日期:" << selectedDate;
        updateAppointmentTable(cachedData);
        return;
    }
    
    // 缓存未命中，从服务器获取
    showLoading();  // 显示加载动画
    
    QJsonObject request;
    request["doctor_id"] = m_doctor.id;
    request["date"] = selectedDate.toString("yyyy-MM-dd");
    
    qDebug() << "从服务器加载预约 - 医生ID:" << m_doctor.id << "日期:" << selectedDate;
    NetworkClient::instance().sendRequest(MSG_GET_PATIENT_LIST, request);
}

void AppointmentWidget::onMessageReceived(MessageType type, const QJsonObject& data) {
    if (type == MSG_GET_PATIENT_LIST_RESPONSE) {
        hideLoading();  // 隐藏加载动画
        
        qDebug() << "收到预约列表响应:" << data;
        if (data["success"].toBool()) {
            QJsonArray patients = data["patients"].toArray();
            qDebug() << "预约数量:" << patients.size();
            
            // 缓存数据
            cacheData(ui->dateEdit->date(), patients);
            
            updateAppointmentTable(patients);
        } else {
            qDebug() << "获取预约列表失败";
            QMessageBox::warning(this, "错误", "获取预约列表失败");
        }
    } else if (type == MSG_START_CONSULTATION_RESPONSE) {
        if (data["success"].toBool()) {
            QMessageBox::information(this, "成功", "已开始接诊");
            // 清除缓存，强制刷新
            m_cache.clear();
            loadAppointments();
        } else {
            QMessageBox::warning(this, "错误", data["message"].toString());
        }
    } else if (type == MSG_FINISH_CONSULTATION_RESPONSE) {
        if (data["success"].toBool()) {
            QMessageBox::information(this, "成功", "就诊已完成");
            // 清除缓存，强制刷新
            m_cache.clear();
            loadAppointments();
        } else {
            QMessageBox::warning(this, "错误", data["message"].toString());
        }
    }
}

void AppointmentWidget::updateAppointmentTable(const QJsonArray& appointments) {
    ui->appointmentTable->setRowCount(0);
    m_appointments = appointments;  // 保存预约数据
    
    for (const QJsonValue& value : appointments) {
        QJsonObject appointment = value.toObject();
        
        int row = ui->appointmentTable->rowCount();
        ui->appointmentTable->insertRow(row);
        
        ui->appointmentTable->setItem(row, 0, 
            new QTableWidgetItem(QString::number(appointment["appointment_id"].toInt())));
        ui->appointmentTable->setItem(row, 1, 
            new QTableWidgetItem(appointment["real_name"].toString())); // 患者姓名
        
        // 格式化预约时间为"日期 时间段"格式
        QString appointmentTimeStr = appointment["appointment_time"].toString();
        QDateTime appointmentTime = QDateTime::fromString(appointmentTimeStr, "yyyy-MM-dd HH:mm:ss");
        if (!appointmentTime.isValid()) {
            appointmentTime = QDateTime::fromString(appointmentTimeStr, Qt::ISODate);
        }
        QString formattedTime;
        if (appointmentTime.isValid()) {
            QString dateStr = appointmentTime.toString("yyyy-MM-dd");
            int hour = appointmentTime.time().hour();
            QString timeSlot = QString("%1:00-%2:00")
                .arg(hour, 2, 10, QChar('0'))
                .arg(hour + 1, 2, 10, QChar('0'));
            formattedTime = QString("%1 %2").arg(dateStr, timeSlot);
        } else {
            formattedTime = appointmentTimeStr;
        }
        
        ui->appointmentTable->setItem(row, 2, 
            new QTableWidgetItem(formattedTime));
        ui->appointmentTable->setItem(row, 3, 
            new QTableWidgetItem(appointment["status"].toString()));
        ui->appointmentTable->setItem(row, 4, 
            new QTableWidgetItem(appointment["symptoms"].toString()));
        
        // 创建操作按钮容器
        QWidget *buttonWidget = new QWidget();
        QHBoxLayout *layout = new QHBoxLayout(buttonWidget);
        layout->setContentsMargins(2, 2, 2, 2);
        layout->setSpacing(4);
        
        QString status = appointment["status"].toString();
        int appointmentId = appointment["appointment_id"].toInt();
        int patientId = appointment["id"].toInt();
        
        // 根据状态显示不同按钮
        if (status == "待就诊") {
            // 开始接诊按钮
            QPushButton *startBtn = new QPushButton("开始接诊");
            startBtn->setMinimumHeight(28);
            startBtn->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
            startBtn->setStyleSheet("QPushButton { background-color: #4CAF50; color: white; border-radius: 3px; }"
                                   "QPushButton:hover { background-color: #45a049; }");
            connect(startBtn, &QPushButton::clicked, this, [this, appointmentId, patientId]() {
                onStartConsultation(appointmentId, patientId);
            });
            layout->addWidget(startBtn);
            
            // 完成就诊按钮（禁用状态）
            QPushButton *finishBtn = new QPushButton("完成就诊");
            finishBtn->setMinimumHeight(28);
            finishBtn->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
            finishBtn->setEnabled(false);
            finishBtn->setStyleSheet("QPushButton { background-color: #CCCCCC; color: #666666; border-radius: 3px; }");
            layout->addWidget(finishBtn);
            
        } else if (status == "就诊中") {
            // 查看详情按钮（可以多次点击进入）
            QPushButton *viewBtn = new QPushButton("查看详情");
            viewBtn->setMinimumHeight(28);
            viewBtn->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
            viewBtn->setStyleSheet("QPushButton { background-color: #9C27B0; color: white; border-radius: 3px; }"
                                  "QPushButton:hover { background-color: #7B1FA2; }");
            connect(viewBtn, &QPushButton::clicked, this, [this, appointmentId, patientId]() {
                emit showPatientDetail(patientId, appointmentId);
            });
            layout->addWidget(viewBtn);
            
            // 完成就诊按钮
            QPushButton *finishBtn = new QPushButton("完成就诊");
            finishBtn->setMinimumHeight(28);
            finishBtn->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
            finishBtn->setStyleSheet("QPushButton { background-color: #2196F3; color: white; border-radius: 3px; }"
                                    "QPushButton:hover { background-color: #0b7dda; }");
            connect(finishBtn, &QPushButton::clicked, this, [this, appointmentId]() {
                onFinishConsultation(appointmentId);
            });
            layout->addWidget(finishBtn);
            
        } else {
            // 已完成或已取消，显示状态
            QLabel *statusLabel = new QLabel(status);
            statusLabel->setAlignment(Qt::AlignCenter);
            statusLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
            layout->addWidget(statusLabel);
        }
        
        ui->appointmentTable->setCellWidget(row, 5, buttonWidget);
        
        ui->appointmentTable->setItem(row, 6, 
            new QTableWidgetItem(QString::number(patientId))); // 患者ID（隐藏列）
    }
    
    ui->countLabel->setText(QString("共 %1 个预约").arg(appointments.size()));
}

void AppointmentWidget::on_appointmentTable_cellDoubleClicked(int row, int column) {
    Q_UNUSED(row);
    Q_UNUSED(column);
    // 取消双击打开功能，只能通过"开始接诊"按钮打开
}

void AppointmentWidget::onStartConsultation(int appointmentId, int patientId) {
    // 发送开始接诊请求
    QJsonObject request;
    request["appointment_id"] = appointmentId;
    
    NetworkClient::instance().sendRequest(MSG_START_CONSULTATION, request);
    
    // 同时打开患者详情页面
    emit showPatientDetail(patientId, appointmentId);
}

void AppointmentWidget::onFinishConsultation(int appointmentId) {
    // 暂时跳过病历检查，直接完成就诊
    // TODO: 后续在服务端实现病历检查
    QMessageBox::StandardButton reply = QMessageBox::question(this, "确认", 
        "确认完成就诊吗？\n\n"
        "提示：完成前请确保已创建病历。",
        QMessageBox::Yes | QMessageBox::No);
    
    if (reply != QMessageBox::Yes) {
        return;
    }
    
    // 发送完成就诊请求
    QJsonObject request;
    request["appointment_id"] = appointmentId;
    
    NetworkClient::instance().sendRequest(MSG_FINISH_CONSULTATION, request);
}

void AppointmentWidget::showLoading() {
    if (m_isLoading) return;
    
    m_isLoading = true;
    
    // 禁用控件，防止重复操作
    ui->dateEdit->setEnabled(false);
    ui->refreshButton->setEnabled(false);
    
    // 调整加载标签位置和大小
    int w = 300;
    int h = 80;
    int x = (this->width() - w) / 2;
    int y = (this->height() - h) / 2;
    
    m_loadingLabel->setGeometry(x, y, w, h);
    m_loadingLabel->raise();  // 置于最上层
    m_loadingLabel->show();
    
    // 添加动画效果
    static int dotCount = 0;
    QTimer::singleShot(500, this, [this]() {
        if (m_isLoading) {
            static QString baseText = "🔄 正在加载数据";
            dotCount = (dotCount + 1) % 4;
            QString dots = QString(".").repeated(dotCount);
            m_loadingLabel->setText(baseText + dots);
        }
    });
    
    qDebug() << "显示加载动画";
}

void AppointmentWidget::hideLoading() {
    if (!m_isLoading) return;
    
    m_isLoading = false;
    m_loadingLabel->hide();
    
    // 恢复控件
    ui->dateEdit->setEnabled(true);
    ui->refreshButton->setEnabled(true);
    
    qDebug() << "隐藏加载动画";
}

